package org.xxpay.mch.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.exception.ServiceException;
import org.xxpay.core.entity.MchInfo;
import org.xxpay.core.entity.PayInterfaceType;
import org.xxpay.mch.common.ctrl.BaseController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@RestController
@RequestMapping(Constant.MCH_CONTROLLER_ROOT_PATH + "/config/pay_interface_type")
public class PayInterfaceTypeController extends BaseController {

    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        judgeRecord();
        JSONObject param = getJsonParam(request);
        PayInterfaceType payInterfaceType = getObject(param, PayInterfaceType.class);
        payInterfaceType.setMustFromTemplate(MchConstant.PUB_YES); //仅查询 强制配置模板的接口类型代码

        MchInfo thisMch = commonService.mchInfoService.findByMchId(getUser().getId());
        payInterfaceType.setPsVal("ifTypeCodeInList", thisMch.getSupportIfTypeList()); //仅查询当前私有商户可见支付接口类型

        int count = commonService.payInterfaceTypeService.count(payInterfaceType);
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<PayInterfaceType> payInterfaceTypeList = commonService.payInterfaceTypeService.select((getPageIndex(param) -1) * getPageSize(param), getPageSize(param), payInterfaceType);
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(payInterfaceTypeList, count));
    }

    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        judgeRecord();
        JSONObject param = getJsonParam(request);
        String ifTypeCode = getStringRequired(param, "ifTypeCode");
        PayInterfaceType payInterfaceType = commonService.payInterfaceTypeService.findByCode(ifTypeCode);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(payInterfaceType));
    }


    /** 校验账号类型和获取的数据是否合法 **/
    private void judgeRecord(){

        if(this.getUser().getType() != MchConstant.MCH_TYPE_PRIVATE){
            throw new ServiceException(RetEnum.RET_MCH_PERMISSION_ERROR);
        }
    }

}
